import Taro from "@tarojs/taro";
import { DocumentNode } from "graphql";
import { useCallback, useState } from "react";
import getToken from "./getToken";


type UseMutationOption = {
    onCompleted?: (data: any) => void,
    onError?: (error: any) => void
}
const useMutation = (
    query: DocumentNode,
    options?: UseMutationOption
) => {
    const { onCompleted, onError } = options || {};
    const [data, setData] = useState()
    const [error, setError] = useState()
    const [loading, setLoading] = useState(false);
    const refetch = useCallback(async (variables?: any) => {
        setLoading(true)
        const token = await getToken()
        return await Taro.request({
            method: "POST",
            url: "http://localhost:14530/graphql",
            header: {
                'Authorization': `Bearer ${token}`
            },
            data: {
                query: query.loc?.source.body,
                variables
            }
        }).then(({ data: { data, errors } }) => {
            if (!!errors) {
                setError(errors[0]);
                if (!!onError) onError(errors[0])
                throw errors[0];
            }
            setData(data)
            if (!!onCompleted) onCompleted(data);
            return data;
        }).catch(e => {
            setError(e);
            if (!!onError) onError(e)
            return e;
        }).finally(() => {
            setLoading(false);
        })
    }, []);
    return [refetch, { data, error, loading }] as const
}
export default useMutation